//
//  SGCorePayment+AliPay.m
//  smartGas
//
//  Created by chen on 2017/11/20.
//  Copyright © 2017年 chen. All rights reserved.
//

#import "SGCorePayment+AliPay.h"
#import "APOrderInfo.h"
#import <AlipaySDK/AlipaySDK.h>
#import "APRSASigner.h"

#import "AppDelegate+SGPaymentOpenURL.h"


@implementation SGCorePayment (AliPay)


#pragma mark - 支付宝支付

/*
 如何集成支付宝
 1. 添加`AlipaySDK.bundle` 和 `AlipaySDK.framework`
 2. 添加系统依赖库
 3. appdelegagte
 4. appScheme
 5. 下单
 5.1 客户端生成订单信息
 5.2 客户端将订单传给后台,生成签名后的订单信息
 */

/**模拟下单,仅测试使用*/
+ (void)aliPayDebug{
    
    // 重要说明
    // 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
    // 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
    // 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    //从支付宝的应用列表里获取
    NSString *appID = kAliAPPId;
    
    // 如下私钥，rsa2PrivateKey 或者 rsaPrivateKey 只需要填入一个
    // 如果商户两个都设置了，优先使用 rsa2PrivateKey
    // rsa2PrivateKey 可以保证商户交易在更加安全的环境下进行，建议使用 rsa2PrivateKey
    // 获取 rsa2PrivateKey，建议使用支付宝提供的公私钥生成工具生成，
    // 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
    NSString *rsa2PrivateKey = @"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCtp3X2k6+516MuSWN6ZZj2vwNr/mpUwYoOx+BVoDOBNsWsOPiLYcOf45Rs9Ww/rLK3qd3gbDognXQmCyxFrZWc/sunF2WMPWzWCy92cW1Xd8tZzy9snYZNqmti0D1EofBxjZ4he21kfqpNqpGt3jbYFf25sXkoizkTHdw4cr+Jbjq1QQeQ80tjW5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YiGvwe93bQUykaSrH0UmNX1/qTXfjYpNb4wYzAWhsTplmvzGRjpeOTfQDpv50ORLMNICxW5wHXwNjF2eE4wYptUsZIWKrvWratUGYhxuLiN2oExyAKykpARf0vw3l1tAKyw+YhTwi8rmGo7AoGAI/7P9q2dVmqovz4fBX4hAdlKw7OMQJiFVMYaVKXAgShSpUjCbPRzMqCnQC1I1ofO+vf2Ohgf+BB8mCT73CmRnn16aE/0vXwDa5Q8tIdWfAfaoG01hUeu3/USE3vQJbVujRsJ5G3lKK5yKhbtw3cQwBuM1wgauj4l4SuYvjDeO0M=";
    NSString *rsaPrivateKey = @"";
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    APOrderInfo* order = [APOrderInfo new];
    
    // NOTE: app_id设置
    order.app_id = appID;
    
    // NOTE: 支付接口名称
    order.method = @"alipay.trade.app.pay";
    
    // NOTE: 参数编码格式
    order.charset = @"utf-8";
    
    // NOTE: 当前时间点
    NSDateFormatter* formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    order.timestamp = [formatter stringFromDate:[NSDate date]];
    
    // NOTE: 支付版本
    order.version = @"1.0";
    
    // NOTE: sign_type 根据商户设置的私钥来决定
    order.sign_type = (rsa2PrivateKey.length > 1)?@"RSA2":@"RSA";
    
    // NOTE: 商品数据
    order.biz_content = [APBizContent new];
    order.biz_content.body = @"我是测试数据";
    order.biz_content.subject = @"1"; //交易标题
    order.biz_content.out_trade_no = [self generateTradeNO]; //订单ID（由商家自行制定）
    order.biz_content.timeout_express = @"30m"; //超时时间设置
    order.biz_content.total_amount = [NSString stringWithFormat:@"%.2f", 0.01]; //商品价格
    
    //将商品信息拼接成字符串
    NSString *orderInfo = [order orderInfoEncoded:NO]; //这个信息签名(传给后台)
    NSString *orderInfoEncoded = [order orderInfoEncoded:YES]; //这个信息需要保留在客户端
    DLog(@"orderSpec = %@",orderInfo);
    
    // NOTE: 获取私钥并将商户信息签名，外部商户的加签过程请务必放在服务端，防止公私钥数据泄露；
    //       需要遵循RSA签名规范，并将签名字符串base64编码和UrlEncode
    NSString *signedString = nil;
    APRSASigner* signer = [[APRSASigner alloc] initWithPrivateKey:((rsa2PrivateKey.length > 1)?rsa2PrivateKey:rsaPrivateKey)];
    if ((rsa2PrivateKey.length > 1)) {
        signedString = [signer signString:orderInfo withRSA2:YES];
    } else {
        signedString = [signer signString:orderInfo withRSA2:NO];
    }
    
    // NOTE: 如果加签成功，则继续执行支付
    if (signedString != nil) {
        //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
        NSString *appScheme = @"hcSmartGas";
        // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
        NSString *orderString = [NSString stringWithFormat:@"%@&sign=%@",
                                 orderInfoEncoded, signedString];
        
        // NOTE: 调用支付结果开始支付
        [[AlipaySDK defaultService] payOrder:orderString
                                  fromScheme:appScheme
                                    callback:^(NSDictionary *resultDic)
         {
             DLog(@"reslut = %@",resultDic);
             [SGAppDelegate aliPayResult:resultDic];
         }];
    }
}

+ (NSString *)generateTradeNO
{
    static int kNumber = 15;
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}

/**生成订单数据字符串,并将数据传给后台,然后后台返回加密后的数据*/
+ (void)alipay_encodeGoodsStringWithContentBody:(NSString *)contentBody//商品描述
                                        subject:(NSString *)subject //订单标题
                                   out_trade_no:(NSString *)out_trade_no //订单ID
                                   total_amount:(CGFloat)total_amount //商品价格
                                       callBack:(void(^)(NSString *orderInfo,NSString *orderInfoEncoded))block
{
    
    APOrderInfo* order = [APOrderInfo new];
    
    // NOTE: app_id设置
    order.app_id = kAliAPPId;
    
    // NOTE: 支付接口名称
    order.method = @"alipay.trade.app.pay";
    
    // NOTE: 参数编码格式
    order.charset = @"utf-8";
    
    // NOTE: 当前时间点
    NSDateFormatter* formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    order.timestamp = [formatter stringFromDate:[NSDate date]];
    
    // NOTE: 支付版本
    order.version = @"1.0";
    
    // NOTE: sign_type 根据商户设置的私钥来决定  RSA2/RSA
    order.sign_type = @"RSA2"; //(rsa2PrivateKey.length > 1)?@"RSA2":@"RSA";
    
    // NOTE: 商品数据
    order.biz_content = [APBizContent new];
    order.biz_content.body = contentBody;
    order.biz_content.subject = subject; //交易标题
    order.biz_content.out_trade_no = out_trade_no; //订单ID（由商家自行制定）
    order.biz_content.timeout_express = @"30m"; //超时时间设置
    order.biz_content.total_amount = [NSString stringWithFormat:@"%.2f", total_amount]; //商品价格
    
    //将商品信息拼接成字符串
    NSString *orderInfo = [order orderInfoEncoded:NO]; //这个信息签名(传给后台)
    NSString *orderInfoEncoded = [order orderInfoEncoded:YES]; //这个信息需要保留在客户端
    DLog(@"orderSpec = %@",orderInfo);
    if (block) {
        block(orderInfo,orderInfoEncoded);
    }
}

+ (void)alipayWithOrderInfoEncoded:(NSString *)orderInfoEncoded
                      signedString:(NSString *)signedString
{
    // NOTE: 如果加签成功，则继续执行支付
    if (signedString != nil) {
        //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
        NSString *appScheme = kPaymentAppScheme;
        // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
        NSString *orderString = [NSString stringWithFormat:@"%@&sign=%@",
                                 orderInfoEncoded, signedString];
        // NOTE: 调用支付结果开始支付
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            DLog(@"reslut = %@",resultDic);
            [SGAppDelegate aliPayResult:resultDic];
        }];
    }
}


+ (void)alipayWithOrderWithOrderString:(NSString *)orderString
{
    //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
    NSString *appScheme = kPaymentAppScheme;
    // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
    //NSString *orderString = [NSString stringWithFormat:@"%@&sign=%@",\
                             orderInfoEncoded, signedString];
    // NOTE: 调用支付结果开始支付
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        DLog(@"reslut = %@",resultDic);
        [SGAppDelegate aliPayResult:resultDic];
    }];
}







+ (void)aliPayGeneratePaymentWithUserId:(NSString *)userId
                                 amount:(NSString *)amount
                                   type:(SGCorePaymentType)paymentType
                              goodsType:(SGCorePaymentGoodsType)goosType
                             relationId:(NSString *)relationId
                                success:(void(^)(NSString *token,NSString *des))success
                                 failed:(void(^)(NSError *error, NSString *des))failed
{
    
    NSString *url = [NSString stringWithFormat:@"%@/busi/payment/payment",
                     HOST_Progress];
    
    NSDictionary *parameters = @{
                                 @"userId":StringValue(userId),
                                 @"payWay":@"2",//支付宝
                                 @"amount":StringValue(amount),
                                 @"type":[NSString stringWithFormat:@"%@",@(paymentType)],
                                 @"goodsType":[NSString stringWithFormat:@"%@",@(goosType)],
                                 @"relationId":StringValue(relationId),
                                 };
    
    [HTTP POST:url
    parameters:parameters
       success:^(id responseObject, NSString *des)
     {
         
         if (success) {
             success(responseObject[@"bring"],des);
         }
         
     } failure:^(NSError *error, NSString *des) {
         if (failed) {
             failed(error,des);
         }
     }];
}



@end

